package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.StrategyComment;
import cn.wolfcode.luowowo.query.QueryObject;
import cn.wolfcode.luowowo.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.repository.StrategyCommentRepository;
import cn.wolfcode.luowowo.service.IStrategyCommentService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
//@Transactional //事务最后处理
public class StrategyCommentServiceImpl implements IStrategyCommentService {

    @Autowired
    private StrategyCommentRepository repository;

    @Autowired
    private MongoTemplate template;


    @Override
    public StrategyComment get(String id) {
        Optional<StrategyComment> optional = repository.findById(id);
        if (optional != null) {
            return optional.get();
        }
        return null;
    }

    @Override
    public Page<StrategyComment> query(StrategyCommentQuery qo) {
        Query query = new Query();
        //分页
        if (StringUtils.hasLength(qo.getStrategyId())){
            query.addCriteria(Criteria.where("strategyId").is(qo.getStrategyId()));
        };
        return DBHelper.query(template, StrategyComment.class,query , qo.getPageable());
    }

    //在攻略中添加评论
    @Override
    public void addComment(StrategyComment comment) {
        //时间和id
        comment.setCreateTime(new Date());
        comment.setId(null);

        //将comment保存到MongoDB
        repository.save(comment);
    }

    //攻略里的评论点赞
    @Override
    public void commentThumb(String cid, String uid) {
        //1.判断用户是点赞还是取消点赞
        //获取存点赞用户的 id 集合 list
        StrategyComment comment = this.get(cid);//评论是存在mongodb中的
        List<String> userList = comment.getThumbuplist();//从评论中拿到存用户id的list

        if (!userList.contains(uid)) {
            //2.不包含，点赞，list中存当前用户的id
            comment.setThumbupnum(comment.getThumbupnum() + 1);
            userList.add(uid);

        }else {
            //3.包含，取消点赞，list中移除当前用户的id
            comment.setThumbupnum(comment.getThumbupnum() - 1);
            userList.remove(uid);
        }
        //4.将list改变的数据同步到mongodb中,更新
        repository.save(comment);
    }
}
